package com.azkj.album.view.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.azkj.album.R;
import com.azkj.album.adapter.ListAdapter;
import com.azkj.album.dto.CategoryBean;
import com.azkj.album.dto.ListData;
import com.azkj.album.dto.MessageEvent;
import com.azkj.album.dto.MessageType;
import com.azkj.album.network.ConfigStorage;
import com.azkj.album.network.NetworkMaster;
import com.azkj.album.network.callback.ServiceCallback;
import com.azkj.album.network.networkframe.bean.BaseResp;
import com.azkj.album.network.networkframe.net.exception.ApiException;
import com.azkj.album.network.utils.ToastUtils;
import com.azkj.album.view.activity.SearchActivity;
import com.azkj.album.view.base.BaseFragment;
import com.azkj.album.view.widgets.dialog.ColorChooseDialog;
import com.azkj.album.view.widgets.dialog.CommonDialog;
import com.azkj.album.view.widgets.dialog.DialogHelper;
import com.azkj.album.view.widgets.staggedrv.GridItemDecoration;
import com.azkj.album.view.widgets.staggedrv.StaggerdRecyclerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class RecoveryFragment extends BaseFragment {

    @BindView(R.id.rv_main)
    StaggerdRecyclerView mRecyclerView;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;

    @BindView(R.id.tv_drop_mark)
    TextView mTvCategory;
    @BindView(R.id.ll_delete)
    View mLlDelete;
    @BindView(R.id.tv_finish)
    TextView tvFinish;
    @BindView(R.id.tv_del_1)
    TextView tvDel1;
    @BindView(R.id.tv_del_2)
    TextView tvDel2;
    @BindView(R.id.tv_del_3)
    TextView tvDel3;
    @BindView(R.id.tv_del_4)
    TextView tvDel4;


    private ListAdapter mAdapter;

    private int mPage = 1;
    private String keyword = "";
    private String categoryId = "";

    private List<CategoryBean> datas = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_recovery;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initData();
    }

    private void initView() {
        mAdapter = new ListAdapter();
        mRecyclerView.link(mAdapter, 2);
        mAdapter.bindToRecyclerView(mRecyclerView.rv);
        mAdapter.setEmptyView(R.layout.list_empty);
        mAdapter.setRecovery(false);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                ListData item = mAdapter.getData().get(position);
                if (mAdapter.getSelList().contains(String.valueOf(item.getId()))) {
                    mAdapter.getSelList().remove(String.valueOf(item.getId()));
                } else {
                    mAdapter.getSelList().add(String.valueOf(item.getId()));
                }
                mAdapter.notifyItemChanged(position);

                mLlDelete.setVisibility(mAdapter.getSelList().size() > 0 ? View.VISIBLE : View.GONE);
            }
        });

        mRecyclerView.addDecoration(new GridItemDecoration(getContext(), 10));
        mRefreshLayout.setEnableAutoLoadMore(false);
        mRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPage++;
                getDataList();

            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPage = 1;
                getDataList();
            }
        });
    }

    private void initData() {
        DialogHelper.showFailDialog("加载中", 0);
        getCategory();
//        getDataList();
    }

    @Subscribe
    public void onMessage(MessageEvent messageEvent) {
        super.onMessage(messageEvent);
        switch (messageEvent.getType()) {
            case MessageType.TYPE_ON_MAIN_DEL:
                mPage = 1;
                getDataList();
                break;
        }
    }

    @OnClick({R.id.tv_search, R.id.tv_drop_mark, R.id.iv_delete_dismiss, R.id.tv_del_1, R.id.tv_del_2, R.id.tv_del_3, R.id.tv_del_4})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_search:
                Intent intent = new Intent(getActivity(), SearchActivity.class);
                intent.putExtra("pageType", 1);
                startActivity(new Intent(intent));

                break;
            case R.id.tv_drop_mark:
                new ColorChooseDialog.Builder(getActivity()).setChoosetList(datas)
                        .setOnClickListener(new ColorChooseDialog.OnClickListener() {
                            @Override
                            public void onClick(Dialog dialog, int position) {
                                dialog.dismiss();
                                mTvCategory.setText(datas.get(position).getName());
                                categoryId = datas.get(position).getId();
                                if ("-1".equals(categoryId)) {
                                    categoryId = "";
                                }
                                mPage = 1;
                                getDataList();
                            }
                        }).show();
                break;
            case R.id.iv_delete_dismiss:
            case R.id.tv_del_3:

                if (mAdapter.getSelList().size() > 0) {
                    mAdapter.getSelList().clear();
                    mAdapter.notifyDataSetChanged();
                }


                mLlDelete.setVisibility(View.GONE);
                tvDel1.setVisibility(View.VISIBLE);
                tvDel2.setVisibility(View.VISIBLE);
                tvDel3.setVisibility(View.GONE);
                tvDel4.setVisibility(View.GONE);
                break;
            case R.id.tv_del_1:
                if (!mAdapter.getSelList().isEmpty()) {
                    new CommonDialog.Builder(getActivity()).setDesc("您是否彻底删除该" + mAdapter.getSelList().size() + "个图册\n" +
                                    "彻底删除后分享链接也会失效")
                            .setButton("取消", "确定")
                            .setBackground(R.mipmap.ic_login_error).
                            setOnClickListener((dialog, confirm) -> {
                                if (confirm) {
                                    deleteComplete();
                                }
                                dialog.dismiss();
                            }).show();
                }
                break;
            case R.id.tv_del_2:
                tvDel1.setVisibility(View.GONE);
                tvDel2.setVisibility(View.GONE);
                tvDel3.setVisibility(View.VISIBLE);
                tvDel4.setVisibility(View.VISIBLE);

                break;
            case R.id.tv_del_4:
                if (!mAdapter.getSelList().isEmpty()) {
                    restore();
                }
                break;
        }
    }

    public void getDataList() {
        NetworkMaster.getInstance().getCommonService().listRecycle(ConfigStorage.getInstance().getToken(),
                String.valueOf(mPage), keyword, categoryId,
                "", "",
                new ServiceCallback<BaseResp<List<ListData>>>() {
                    @Override
                    public void onSuccess(BaseResp data) {
                        DialogHelper.hideDialog();
                        mRefreshLayout.finishLoadMore(true);
                        mRefreshLayout.finishRefresh(true);
                        if (data.getCode() == 1) {
                            List<ListData> list = (List<ListData>) data.getData();
                            if (mPage == 1) {
                                mAdapter.setNewData(list);
                            } else {
                                mAdapter.addData(list);
                            }
                            //处理数据
                            if (list.size() < 10) {
                                tvFinish.setVisibility(View.VISIBLE);
                                mRefreshLayout.setEnableLoadMore(false);
                            } else {
                                tvFinish.setVisibility(View.GONE);
                                mRefreshLayout.setEnableLoadMore(true);
                            }
                        } else {
                            ToastUtils.showCenterToast(data.getMsg());
                        }

                    }

                    @Override
                    public void onError(ApiException apiException) {
                        DialogHelper.hideDialog();
                        mRefreshLayout.finishLoadMore(true);
                        mRefreshLayout.finishRefresh(true);
                        ToastUtils.showCenterToast(apiException.errorInfo.error);
                    }
                });
    }

    private void getCategory() {
        NetworkMaster.getInstance().getCommonService().mainCategory(new ServiceCallback<BaseResp<List<CategoryBean>>>() {
            @Override
            public void onSuccess(BaseResp<List<CategoryBean>> jsonObj) {
                CategoryBean all = new CategoryBean();
                all.setId("-1");
                all.setName("全部");
                datas.add(all);
                datas.addAll(jsonObj.getData());
            }

            @Override
            public void onError(ApiException apiException) {
                ToastUtils.showCenterToast(apiException.errorInfo.error);
            }
        });
    }

    private void deleteComplete() {
        StringBuilder idsSb = new StringBuilder();
        for (String id : mAdapter.getSelList()) {
            idsSb.append(id + ",");
        }
        NetworkMaster.getInstance().getCommonService().delComplete(ConfigStorage.getInstance().getToken(), idsSb.toString(), new ServiceCallback() {
            @Override
            public void onSuccess(Object jsonObj) {
                for (String id : mAdapter.getSelList()) {
                    ListData item = mAdapter.getItemById(id);
                    int position = mAdapter.getItemPosition(item);
                    mAdapter.notifyItemRemoved(position);
                    mAdapter.getData().remove(item);
                }
                mAdapter.getSelList().clear();
                mLlDelete.setVisibility(View.GONE);
                tvDel1.setVisibility(View.VISIBLE);
                tvDel2.setVisibility(View.VISIBLE);
                tvDel3.setVisibility(View.GONE);
                tvDel4.setVisibility(View.GONE);
            }

            @Override
            public void onError(ApiException apiException) {
                ToastUtils.showCenterToast(apiException.errorInfo.error);
            }
        });
    }

    private void restore() {
        StringBuilder idsSb = new StringBuilder();
        for (String id : mAdapter.getSelList()) {
            idsSb.append(id + ",");
        }
        NetworkMaster.getInstance().getCommonService().restore(ConfigStorage.getInstance().getToken(), idsSb.toString(), new ServiceCallback() {
            @Override
            public void onSuccess(Object jsonObj) {
                for (String id : mAdapter.getSelList()) {
                    ListData item = mAdapter.getItemById(id);
                    int position = mAdapter.getItemPosition(item);
                    mAdapter.notifyItemRemoved(position);
                    mAdapter.getData().remove(item);
                }
                mAdapter.getSelList().clear();
                EventBus.getDefault().post(new MessageEvent(MessageType.TYPE_ON_MAIN_RECOVERY));
                ToastUtils.showCenterToast("恢复成功，请在首页查看。");
                mLlDelete.setVisibility(View.GONE);
                tvDel1.setVisibility(View.VISIBLE);
                tvDel2.setVisibility(View.VISIBLE);
                tvDel3.setVisibility(View.GONE);
                tvDel4.setVisibility(View.GONE);

            }

            @Override
            public void onError(ApiException apiException) {
                ToastUtils.showCenterToast(apiException.errorInfo.error);
            }
        });
    }


    @Override
    public void onVisible() {
        mPage = 1;
        getDataList();

    }
}
